package com.zhx.aspect;

import com.zhx.dao.LoginLogDao;
import com.zhx.dao.UserDao;
import com.zhx.domain.LoginLog;
import com.zhx.domain.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: web-framework-spring
 * @author: zhx
 * @create: 2021-05-17 23:27
 **/
@Aspect
@Component
public class LogAspectj {
    private static Logger logger = LoggerFactory.getLogger(LogAspectj.class);

    @Autowired
    private LoginLogDao loginLogDao;

    @Pointcut("execution(* com.zhx.dao.UserDao.insertUser(..))"
                +"|| execution(* com.zhx.dao.UserDao.updateLoginInfo(..))")
    public void daoAspect(){}

    /**
     * 后置返回通知
     * dao切入点
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @AfterReturning(value = "daoAspect()",returning = "user")
    public void AfterReturning(User user){
        if (user!=null){
            logger.info("切面返回信息："+user.toString());
            LoginLog loginLog = new LoginLog();
            loginLog.setUserId(user.getUserId());
            loginLog.setIp(user.getLastIp());
            //如果登陆日期不为空，就是登陆
            if (user.getLastvisit()!=null && !user.getLastvisit().equals("")){
                loginLog.setLoginDate(user.getLastvisit());
                loginLog.setRegisterDate(null);
            }
            //如果注册日期不为空，就是注册
            if (user.getRegisterTime()!=null && !user.getRegisterTime().equals("")){
                loginLog.setRegisterDate(user.getRegisterTime());
                loginLog.setLoginDate(null);
            }
            loginLogDao.insertLogLog(loginLog);
            logger.info("插入日志表信息成功");
        }else{
            logger.info("插入用户日志失败");
        }
    }
}
